package com.qth.valet.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qth.valet.common.annotation.Logs;
import com.qth.valet.common.annotation.Release;
import com.qth.valet.common.annotation.RepeatSubmit;
import com.qth.valet.common.theadlocal.UserOrDriverIdHolder;
import com.qth.valet.common.utils.LoginTypeConstants;
import com.qth.valet.common.utils.ResponseResult;
import com.qth.valet.common.utils.StatusConstants;
import com.qth.valet.entity.po.Users;
import com.qth.valet.payment.WxPaymentConfig;
import com.qth.valet.service.UsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/qth/users")
public class UsersController {

    private final UsersService usersService;

    private final RestTemplate restTemplate;

    private final WxPaymentConfig wxPaymentConfig;

    @GetMapping("/info")
    public ResponseResult<Users> getInfo() {
        LambdaQueryWrapper<Users> usersQueryWrapper = new LambdaQueryWrapper<>();
        usersQueryWrapper.eq(Users::getId, UserOrDriverIdHolder.getUserId());
        List<Users> list = usersService.list(usersQueryWrapper);

        if(list.isEmpty()){
            return ResponseResult.fail("用户不存在");
        }
        return ResponseResult.success("用户信息", list.get(0));
    }

    @Release
    @PostMapping("/login")
    public ResponseResult<String> login(@RequestBody Users users){
        LambdaQueryWrapper<Users> usersQueryWrapper = new LambdaQueryWrapper<>();
        usersQueryWrapper.eq(Users::getOpenId, users.getOpenId());
        List<Users> list = usersService.list(usersQueryWrapper);

        if(list.isEmpty()){
            return ResponseResult.fail("用户不存在");
        }
        StpUtil.login(users.getOpenId(), LoginTypeConstants.USER);
        return ResponseResult.success("TOKEN", StpUtil.getTokenValue());
    }

    @Logs( operation  = "用户注册")
    @PostMapping("/register")
    @RepeatSubmit
    @Release
    public ResponseResult<Void> register(@RequestBody Users users){
        users.setStatus(StatusConstants.USER_NORMAL);
        usersService.save(users);
        return ResponseResult.success();
    }

    @Logs(operation = "用户是否已注册")
    @PostMapping("/hasRegistered")
    @Release
    public ResponseResult<Boolean> hasRegistered(@RequestBody Users users){
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getOpenId, users.getOpenId());

        List<Users> list = usersService.list(queryWrapper);
        return ResponseResult.success(!list.isEmpty());
    }

    //@Logs(operation = "微信获取用户openid")
    @GetMapping("/weixin")
    @Release
    public ResponseResult<String> weixin(String jsCode){
        String url = StatusConstants.WEIXIN_URL + "&appid=" + wxPaymentConfig.getAppId() + "&secret=" + wxPaymentConfig.getSecret() + "&js_code=" + jsCode;
        String forObject = restTemplate.getForObject(url, String.class);

        JSONObject json = JSONUtil.parseObj(forObject);
        String openid = json.getStr("openid");
        if(StrUtil.isBlank(openid)){
            return ResponseResult.fail("查询失败。");
        }

        return ResponseResult.success("查询成功。", openid);
    }

    /**
     * 微信用户用code换取手机号
     */
    @GetMapping("/getWeixinUserPhone/{code}")
    public ResponseResult<String> getWeixinUserPhone(@PathVariable("code") String code){

        // 第一步：小程序id、secret换access_token
        String url1 = "https://api.weixin.qq.com/cgi-bin/stable_token";
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.set("appid", wxPaymentConfig.getAppId());
        jsonObject1.set("secret", wxPaymentConfig.getSecret());
        jsonObject1.set("grant_type", "client_credential");
        String res1 = restTemplate.postForObject(url1, jsonObject1, String.class);
        JSONObject jsonRes1 = JSONUtil.parseObj(res1);
        String accessToken = jsonRes1.getStr("access_token");

        // 第二步：用户code、access_token换手机号
        String url2 = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.set("code", code);
        String res2 = restTemplate.postForObject(url2, jsonObject2, String.class);
        JSONObject jsonRes2 = JSONUtil.parseObj(res2);
        JSONObject phoneInfo = jsonRes2.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getStr("phoneNumber");

        return ResponseResult.success("", phoneNumber);
    }

    @PostMapping("/updateUser")
    public ResponseResult<Users> updateUser(@RequestBody Users users){
        LambdaUpdateWrapper<Users> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Users::getId, UserOrDriverIdHolder.getUserId());
        if(!StrUtil.isBlank(users.getUsername())){
            lambdaUpdateWrapper.set(Users::getUsername, users.getUsername());
        }
        if(!StrUtil.isBlank(users.getAvatar())){
            lambdaUpdateWrapper.set(Users::getAvatar, users.getAvatar());
        }
        if(!StrUtil.isBlank(users.getPhone())){
            lambdaUpdateWrapper.set(Users::getPhone, users.getPhone());
        }
        boolean flag =  usersService.update(lambdaUpdateWrapper);
        if(flag){
            return ResponseResult.success(usersService.getById(UserOrDriverIdHolder.getUserId()));
        }
        return ResponseResult.fail("用户修改失败");
    }

}
